import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { RoleEntity } from './role.entity';
import { In, Repository } from 'typeorm';
import { isEmpty } from 'lodash';
import { ROOT_ROLE_ID } from '../constant/system.constant';
@Injectable()
export class RoleService {
  constructor(
    @InjectRepository(RoleEntity)
    private readonly roleRepository: Repository<RoleEntity>
  ) {}
  // 是否是admin 权限
  hasAdminRole(roleIds: number[]): boolean {
    return roleIds.includes(ROOT_ROLE_ID);
  }

  // 根据用户id获取角色id
  async getRoleIdsByUser(id: number): Promise<number[]> {
    const roles = await this.roleRepository.find({
      where: {
        users: { id }
      }
    });
    if (!isEmpty(roles)) {
      return roles.map((role) => role.id);
    }
    return [];
  }
  // 根据角色id获取角色value
  async getRoleValues(ids: number[]): Promise<string[]> {
    const roles = await this.roleRepository.findBy({
      id: In(ids)
    });
    if (!isEmpty(roles)) {
      return roles.map((role) => role.value);
    }
    return [];
  }
}
